package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.enums.SmsSignEnum;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.SmsTemplateRequest;
import com.ytjj.qmyx.supplychain.common.model.response.SmsTemplateResponse;
import com.ytjj.qmyx.supplychain.common.utils.TokenUtil;
import com.ytjj.qmyx.supplychain.mapper.SmsTemplateMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxShopInfo;
import com.ytjj.qmyx.supplychain.mapper.entity.YxSmsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jiawei
 * @date 2024年06月06日 10:09
 * @describe
 */
@Slf4j
@Service
public class SmsManageService {

    @Resource
    SmsTemplateMapper smsTemplateMapper;
    @Resource
    ShopInfoService shopInfoService;

    /**
     * 分页查询模板
     */
    public CommonPage<YxSmsTemplate> getTemplateOnePage(SmsTemplateRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<YxSmsTemplate> templateOnePage = smsTemplateMapper.getTemplateList(request);
        CommonPage<YxSmsTemplate> smsTemplateResponseCommonPage = CommonPage.restPage(templateOnePage);
        return smsTemplateResponseCommonPage;
    }

    /**
     * 新增或修改短信模板
     */
    public CommonResult addOrEditTemplate(YxSmsTemplate smsTemplate) {
        //校验签名
        if (StringUtils.isEmpty(smsTemplate.getSign()) || !SmsSignEnum.isExist(smsTemplate.getSign())) {
            return CommonResult.failed("非法签名！");
        }
        if(StringUtils.isEmpty(smsTemplate.getTemplateName())){
            return CommonResult.failed("模板名称不能为空！");
        }
        YxSmsTemplate template = new YxSmsTemplate();
        String content = smsTemplate.getContent();
        template.setTemplateName(smsTemplate.getTemplateName());
        template.setSign(smsTemplate.getSign());
        template.setContent(content);
        //校验占位符的正确性
        List<String> strings = matchCharacter(content);
        for (int i = 0; i < strings.size(); i++) {
            String placeholder = strings.get(i).replace("{", "").replace("}", "");
            String[] placeholderIndex = placeholder.split(",");
            int startIndex = Integer.valueOf(placeholderIndex[0]);
            int endIndex = Integer.valueOf(placeholderIndex[1]);
            if (startIndex >= endIndex) {
                return CommonResult.failed("占位符内的开始值不能大于或等于终止值！");
            }
        }
        template.setTemplateType(smsTemplate.getTemplateType());
        //设置变量的数量
        template.setVariableNumber(strings.size());
        //修改
        if (null != smsTemplate.getId()) {
            template.setId(smsTemplate.getId());
            template.setUpdateTime(new Date());
            template.setUpdateId(smsTemplate.getUpdateId());
            smsTemplateMapper.updateByPrimaryKeySelective(template);
        } else { //新增
            String partentId = TokenUtil.getPartentId();
            if(StringUtils.isEmpty(partentId)){
                return CommonResult.failed("参数校验失败！");
            }
            YxShopInfo shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
            template.setCreateId(smsTemplate.getCreateId());
            template.setCreateTime(new Date());
            template.setShopId(shopInfo.getShopId());
            smsTemplateMapper.insertSelective(template);
        }
        return CommonResult.success();
    }


    /**
     * 修改短信模板状态
     */
    public Integer changeStatus(Integer id, Integer status) {
        YxSmsTemplate template = new YxSmsTemplate();
        template.setId(id);
        template.setStatus(status);
        return smsTemplateMapper.updateByPrimaryKeySelective(template);
    }

    /**
     * 删除模板
     */
    public Integer delete(Integer id) {
        YxSmsTemplate template = new YxSmsTemplate();
        template.setId(id);
        template.setStatus(0);
        template.setIsDeleted(1);
        return smsTemplateMapper.updateByPrimaryKeySelective(template);
    }



    /**
     * 正则匹配占位符
     *
     * @param content 待匹配的内容
     * @return Integer
     */
    public List<String> matchCharacter(String content) {
        List<String> charaList = new ArrayList<>();
        if (StringUtils.isNotEmpty(content)) {
            Pattern pattern = Pattern.compile("\\{(\\d+,\\d+)\\}");
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                String group = matcher.group();
                group = group.replaceFirst("，", ",");
                charaList.add(group);
                log.info("匹配到短信内容的占位符是：" + group);
            }
        }
        return charaList;
    }
}
